package edu.hrbu.trade01.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hrbu.trade01.entity.Firm;
import edu.hrbu.trade01.mapper.FirmMapper;
import edu.hrbu.trade01.service.FirmService;
import edu.hrbu.trade01.util.ConstUtil;
import edu.hrbu.trade01.vo.AnalysisVo;
import edu.hrbu.trade01.vo.FirmQueryVo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 徐登宇
 */
@Service
public class FirmServiceImpl extends ServiceImpl<FirmMapper, Firm> implements FirmService {
    @Override
    public Page<Firm> getPageWithCondition(int page, int limit, String firmStr, int isVip) {
        Page<Firm> pageParam = new Page<>(page, limit);
        LambdaQueryWrapper<Firm> wrapperFirm = new LambdaQueryWrapper<>();

        if (isVip == ConstUtil.IS_VIP) {
            wrapperFirm.eq(Firm::getIsVip, 1);
        } else wrapperFirm.eq(Firm::getIsVip, 0);

        if (!ObjectUtils.isEmpty(firmStr)) {
            FirmQueryVo firmQueryVo = JSONUtil.toBean(firmStr, FirmQueryVo.class);
            if (firmQueryVo!=null) {
                String name = firmQueryVo.getName();
                String business = firmQueryVo.getBusiness();
                LocalDateTime preTime = firmQueryVo.getTime1();
                LocalDateTime postTime = firmQueryVo.getTime2();
                if (!ObjectUtils.isEmpty(name))
                    wrapperFirm.like(Firm::getName, name);
                if (!ObjectUtils.isEmpty(business))
                    wrapperFirm.like(Firm::getBusiness, business);
                if (!ObjectUtils.isEmpty(preTime))
                    wrapperFirm.ge(Firm::getCreateTime, preTime);
                if (!ObjectUtils.isEmpty(postTime))
                    wrapperFirm.le(Firm::getCreateTime, postTime);
            }
        }
        return page(pageParam, wrapperFirm);
    }

    @Override
    public List<AnalysisVo> analysis() {
        LambdaQueryWrapper<Firm> wrapperFirm = new LambdaQueryWrapper<>();
        wrapperFirm.eq(Firm::getIsVip, 1);
        long allCount = count();
        long vipCount = count(wrapperFirm);
        AnalysisVo allVo = new AnalysisVo();
        allVo.setType("所有企业");
        allVo.setCount(allCount);
        AnalysisVo vipVo = new AnalysisVo();
        vipVo.setType("VIP企业");
        vipVo.setCount(vipCount);
        return new ArrayList<AnalysisVo>(Arrays.asList(allVo,vipVo));
    }
}
